import { useState, useEffect } from "react";
import Navbar from "../../compoents/Navbar";
import { useNavigate, useLocation } from "react-router-dom";
import style from "./index.module.css";
import { Stepper, Button, ActionSheet, Input } from "antd-mobile";
import { EnvironmentOutline, RightOutline } from "antd-mobile-icons";

interface Report {
  id: number;
  title: string;
  type: string;
  typeColor: string;
  quantity: number;
}
function Index() {
  const navigate = useNavigate();
  const { state } = useLocation();
  console.log("state", state);

  // 使用state中的报告数据
  const reports = state?.reports || [];

  const [reportQuantities, setReportQuantities] = useState(
    reports.reduce((acc: Record<number, number>, report: Report) => {
      acc[report.id] = report.quantity || 0;
      return acc;
    }, {} as Record<number, number>)
  );

  // 个人信息状态
  const [userInfo, setUserInfo] = useState({
    name: '王小柯',
    phone: '13666666666',
    address: '四川省成都市锦江区666号'
  });

  // 地址选择相关状态
  const [showAddressSheet, setShowAddressSheet] = useState(false);
  const [showPhoneSheet, setShowPhoneSheet] = useState(false);
  const [showNameSheet, setShowNameSheet] = useState(false);

  // 临时输入状态
  const [tempName, setTempName] = useState('');
  const [tempPhone, setTempPhone] = useState('');

  // 地址选择器数据
  const addressOptions = [
    { label: '四川省成都市锦江区666号', value: '四川省成都市锦江区666号' },
    { label: '四川省成都市武侯区123号', value: '四川省成都市武侯区123号' },
    { label: '四川省成都市青羊区456号', value: '四川省成都市青羊区456号' },
    { label: '四川省成都市金牛区789号', value: '四川省成都市金牛区789号' },
  ];

  // 从localStorage加载个人信息
  useEffect(() => {
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      setUserInfo(JSON.parse(savedUserInfo));
    }
  }, []);

  // 保存个人信息到localStorage
  const saveUserInfo = (newUserInfo: typeof userInfo) => {
    setUserInfo(newUserInfo);
    localStorage.setItem('userInfo', JSON.stringify(newUserInfo));
  };

  // 计算总金额
  const totalAmount =
    (Object.values(reportQuantities) as number[]).reduce(
      (sum: number, qty: number) => sum + qty * 5,
      0
    ) + 2;
  const handleQuantityChange = (reportId: number, value: number) => {
    setReportQuantities((prev: Record<number, number>) => ({
      ...prev,
      [reportId]: value,
    }));
  };

  // 处理个人信息选择
  const handleUserInfoClick = () => {
    ActionSheet.show({
      actions: [
        { text: '修改姓名', key: 'name' },
        { text: '修改电话', key: 'phone' },
        { text: '修改地址', key: 'address' },
      ],
      onAction: (action) => {
        switch (action.key) {
          case 'name':
            setTempName(userInfo.name);
            setShowNameSheet(true);
            break;
          case 'phone':
            setTempPhone(userInfo.phone);
            setShowPhoneSheet(true);
            break;
          case 'address':
            setShowAddressSheet(true);
            break;
        }
      },
    });
  };

  // 处理姓名输入
  const handleNameInput = (value: string) => {
    setTempName(value);
  };

  // 处理电话输入
  const handlePhoneInput = (value: string) => {
    setTempPhone(value);
  };

  // 确认姓名修改
  const handleNameConfirm = () => {
    if (tempName.trim()) {
      const newUserInfo = { ...userInfo, name: tempName.trim() };
      saveUserInfo(newUserInfo);
    }
    setShowNameSheet(false);
  };

  // 确认电话修改
  const handlePhoneConfirm = () => {
    if (tempPhone.trim()) {
      const newUserInfo = { ...userInfo, phone: tempPhone.trim() };
      saveUserInfo(newUserInfo);
    }
    setShowPhoneSheet(false);
  };

  // 处理地址修改
  const handleAddressChange = (value: string) => {
    const newUserInfo = { ...userInfo, address: value };
    saveUserInfo(newUserInfo);
    setShowAddressSheet(false);
  };

  // 处理地址选择
  const handleAddressSelect = (value: string) => {
    handleAddressChange(value);
  };

  const handleSubmit = () => {
    console.log("提交订单", { reportQuantities, totalAmount, userInfo });
    // 将申请数据保存到localStorage
    const newApplication = {
      id: Date.now().toString(),
      title: '门诊报告打印',
      status: 'pending',
      hospital: '四川省保健院北苑',
      applicant: userInfo.name, // 使用用户选择的姓名
      applicationTime: new Date().toLocaleString('zh-CN'),
      orderAmount: totalAmount,
      reports: reports,
      reportQuantities: reportQuantities,
      userInfo: userInfo // 添加用户选择的个人信息
    };
    
    // 获取现有记录
    const existingRecords = JSON.parse(localStorage.getItem('applicationRecords') || '[]');
    const updatedRecords = [newApplication, ...existingRecords];
    localStorage.setItem('applicationRecords', JSON.stringify(updatedRecords));
    
    navigate("/WriteMsgs", { 
      state: { 
        newApplication: true,
        totalAmount,
        reports,
        reportQuantities,
        userInfo // 将用户选择的个人信息一起传递到下一个页面
      }
    });
  };

  return (
    <div className={style.container}>
      <Navbar showBack onBack={() => navigate(-1)} title="填写信息填写" />
      <div className={style.content}>
        <div className={style.progressContainer}>
          <div className={style.progressStep}>
            <div className={style.stepCircle}>1</div>
            <div className={style.stepLine}></div>
            <div className={`${style.stepCircle} ${style.active}`}>2</div>
            <div className={style.stepLine}></div>
            <div className={style.stepCircle}>3</div>
          </div>
          <div className={style.stepLabels}>
            <span className={style.stepLabel}>基本信息</span>
            <span className={`${style.stepLabel} ${style.active}`}>
              邮寄方式
            </span>
            <span className={style.stepLabel}>完成申请</span>
          </div>
        </div>

        {/* 用户信息区域 */}
        <div className={style.userInfoSection}>
          <div className={style.userInfo} onClick={handleUserInfoClick}>
            <div className={style.locationIcon}>
              <EnvironmentOutline
                style={{ fontSize: "20px", color: "#1890ff" }}
              />
            </div>
            <div className={style.userDetails}>
              <div className={style.userDetailsBox}>
                <div className={style.userName}>{userInfo.name}</div>
                <div className={style.userPhone}>{userInfo.phone}</div>
              </div>

              <div className={style.userAddress}>{userInfo.address}</div>
            </div>
            <div className={style.arrowIcon}>
              <RightOutline style={{ fontSize: "16px", color: "#333" }} />
            </div>
          </div>
        </div>

        {/* 分割线 */}
        <div className={style.divider}></div>

        {/* 复印内容区域 */}
        <div className={style.copyContentSection}>
          <div className={style.sectionTitle}>复印内容</div>
          <div className={style.reportsList}>
            {reports.map((report: Report) => (
              <div key={report.id} className={style.reportItem}>
                <div className={style.reportInfo}>
                  <span className={style.reportNumber}>{report.id}.</span>
                  <span className={style.reportTitle}>{report.title}</span>
                  <span
                    className={style.reportType}
                    style={{ backgroundColor: report.typeColor }}
                  >
                    {report.type}
                  </span>
                </div>
                <div className={style.quantitySelector}>
                  <Stepper
                    value={reportQuantities[report.id] || 0}
                    onChange={(value) =>
                      handleQuantityChange(report.id, value || 0)
                    }
                    min={0}
                    max={10}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 服务须知区域 */}
        <div className={style.serviceInstructionsSection}>
          <div className={style.sectionTitle}>服务须知</div>
          <div className={style.instructionsList}>
            <div className={style.instructionItem}>
              <span className={style.instructionNumber}>1、</span>
              <span className={style.instructionText}>
                每份报告固定价格 5 元,服务费固定2元
              </span>
            </div>
            <div className={style.instructionItem}>
              <span className={style.instructionNumber}>2、</span>
              <span className={style.instructionText}>
                邮寄费用为顺丰到付,由患者自费
              </span>
            </div>
            <div className={style.instructionItem}>
              <span className={style.instructionNumber}>3、</span>
              <span className={style.instructionText}>
                下单后,医院审核通过后将在7天内完成邮寄
              </span>
            </div>
            <div className={style.instructionItem}>
              <span className={style.instructionNumber}>4、</span>
              <span className={style.instructionText}>
                为了保证隐私和安全,我们要求收件时进行身份确认。
              </span>
            </div>
          </div>
        </div>
      </div>

       {/* 底部提交区域 */}
       <div className={style.footerSection}>
         <div className={style.amountInfo}>
           <span className={style.amountLabel}>金额:</span>
           <span className={style.amountValue}>¥{totalAmount.toFixed(2)}</span>
         </div>
         <Button className={style.submitButton} onClick={()=>handleSubmit()}>
           提交
         </Button>
       </div>

       {/* 姓名修改弹窗 */}
       {showNameSheet && (
         <div className={style.inputModal}>
           <div className={style.modalContent}>
             <div className={style.modalTitle}>修改姓名</div>
             <Input
               placeholder="请输入姓名"
               value={tempName}
               onChange={handleNameInput}
               className={style.modalInput}
             />
             <div className={style.modalButtons}>
               <Button 
                 className={style.cancelBtn}
                 onClick={() => setShowNameSheet(false)}
               >
                 取消
               </Button>
               <Button 
                 className={style.confirmBtn}
                 onClick={handleNameConfirm}
               >
                 确定
               </Button>
             </div>
           </div>
         </div>
       )}

       {/* 电话修改弹窗 */}
       {showPhoneSheet && (
         <div className={style.inputModal}>
           <div className={style.modalContent}>
             <div className={style.modalTitle}>修改电话</div>
             <Input
               placeholder="请输入电话"
               value={tempPhone}
               onChange={handlePhoneInput}
               className={style.modalInput}
             />
             <div className={style.modalButtons}>
               <Button 
                 className={style.cancelBtn}
                 onClick={() => setShowPhoneSheet(false)}
               >
                 取消
               </Button>
               <Button 
                 className={style.confirmBtn}
                 onClick={handlePhoneConfirm}
               >
                 确定
               </Button>
             </div>
           </div>
         </div>
       )}

       {/* 地址修改弹窗 */}
       {showAddressSheet && (
         <div className={style.inputModal}>
           <div className={style.modalContent}>
             <div className={style.modalTitle}>修改地址</div>
             <div className={style.addressList}>
               {addressOptions.map((option, index) => (
                 <div 
                   key={index}
                   className={`${style.addressOption} ${userInfo.address === option.value ? style.selected : ''}`}
                   onClick={() => handleAddressSelect(option.value)}
                 >
                   {option.label}
                 </div>
               ))}
             </div>
             <div className={style.modalButtons}>
               <Button 
                 className={style.cancelBtn}
                 onClick={() => setShowAddressSheet(false)}
               >
                 取消
               </Button>
             </div>
           </div>
         </div>
       )}
     </div>
   );
 }
 
 export default Index;
